# faceRecognView.py
from faceRecogn import faceRecognService as db
from utils.clients import connected_clients
from flask import Blueprint, jsonify, request, current_app
from flask_sockets import Sockets
import json
from apscheduler.schedulers.background import BackgroundScheduler

faceRecogn = Blueprint('faceRecogn', __name__,url_prefix="/api")
sockets = Sockets()  # 创建 Sockets 实例

#ws连接的根目录
@sockets.route('/')
def websocket(ws):
    # 添加新的客户端到集合中
    connected_clients.add(ws)
    try:
        while not ws.closed:
            message = ws.receive()
            # ws连接断开会发送一条None消息过来
            if message is not None:
                msg = json.loads(message)
                cmd = msg.get('cmd', 'Not Exist CMD')
                # 配置心跳包
                if cmd == 'ping':
                    pong_message = {
                        "cmd": "pong",
                    }
                    ws.send(json.dumps(pong_message))
                    print(msg)
                    db.update_status(msg)
                # 接收客户端声明
                elif cmd == 'declare':
                    print(f"Client declare Msg: {msg}")
                    db.update_status(msg)
                # 设备回复
                elif cmd == "to_client":
                    # 下发人员回复
                    if msg.get('data')['cmd'] == 'addUserRet':
                        # print(msg)
                        db.release_equipment(msg)
                    # 删除人员回复
                    elif msg.get('data')['cmd'] == 'delUserRet':
                        # print(msg)
                        db.delUser(msg)
                # 指令返回结果
                else:
                    print(f"Client Return Msg: {msg}")
    finally:
        # 移除断开连接的客户端
        connected_clients.discard(ws)

#将信息广播给其他client
def broadcast_msg(message):
    # 遍历所有客户端
    for client in connected_clients:
        if client.closed is False:
            try:
                client.send(message)  # 发送消息给其他客户端
            except Exception as e:
                print(f"Failed to send message to client: {e}")
                connected_clients.discard(client)  # 移除出现问题的客户端

#人脸识别成功数据
@faceRecogn.route('/v1/record/face', methods=['POST'])
def faceRecogn_data():
    formdata = request.json
    result = db.faceRecogn_data(formdata)
    print(result)
    return jsonify(result)

#陌生人数据：包括了设备端录入的人脸信息
@faceRecogn.route('/v1/stranger', methods=['POST'])
def get_stranger_data():
    formdata = request.json
    print(formdata)
    data = {
        "Result":0,
        "Msg":"更新成功"
    }
    return jsonify(data)


def auto_update_status():
    db.auto_update_status()

@faceRecogn.before_app_request
def setup_scheduler():
    print('开始定时任务')
    scheduler = BackgroundScheduler()
    # 配置定时任务
    scheduler.add_job(auto_update_status, 'interval', seconds=5)  # 每 10 s执行一次任务
    scheduler.start()
    current_app.scheduler = scheduler  # 将调度器保存到应用上下文中


#测试用
@faceRecogn.route('/',methods=['GET'])
def info():
    # 获取查询字符串参数，读取到的参数是字符串类型；用print(type(pageSize),type(pageCurrent),type(searchValue))验证
    pageSize = request.args.get('pageSize',default=10,type=int)
    pageCurrent = request.args.get('page',default=1,type=int)
    userName = request.args.get('name',default=None,type=str)
    print(pageCurrent,type(pageCurrent),pageSize,userName,type(userName))
    return ("连接成功")

